package WEB.JDBC;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @ClassName JDBCDemo
 * @Description JDBC DQL 遍历数据
 * @Author 2214361854
 * @Date 2022/3/9 14:31
 * @Version 1.0
 */
public class JDBCDemo3 {
    public static void main(String[] args) throws Exception {
        //127.0.0.1
        String url = "jdbc:mysql://localhost:3306/abc?serverTimezone=UTC&?useUnicode=true&characterEncoding=utf8&useSSL=false";
        String username = "root";
        String password = "root";
        Connection coon = DriverManager.getConnection(url, username, password);

        //获取执行SQL对象
        Statement statement = coon.createStatement();

//        //定义SQL
//        String sql1 = "update student set gender='男' where id=1";
//        //执行SQL DDL执行成功也可能返回0
//        //DML执行后 受影响的行数
//        int cont1 = statement.executeUpdate(sql1);
//        //DML处理结果
//        if (cont1 > 0) {
//            System.out.println("成功");
//        } else {
//            System.out.println("失败");
//        }

        String slq2 = "SELECT * FROM student";
        ResultSet resultSet = statement.executeQuery(slq2);

        List<Student> list = new ArrayList<>();

        //遍历 resultSet
        while (resultSet.next()) {
//            int id = resultSet.getInt(1);
//            String name = resultSet.getString(2);
//            String sex = resultSet.getString(3);
//            System.out.println(id+","+name+","+sex);

            //获取数据，并添加到list
            Student student = new Student(resultSet.getInt("id"),resultSet.getString("name"),resultSet.getString("sex"));
            list.add(student);
        }
        System.out.println(list);
        //释放资源
//        statement.close();
        resultSet.close();
        coon.close();
    }
}

class Student{
    int id;
    String name;
    String sex;

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                '}';
    }

    public Student(int id, String name, String sex) {
        this.id = id;
        this.name = name;
        this.sex = sex;
    }

    public Student() {
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }
}